package com.alpha.common.utils.pay.ways;

import com.alpha.common.utils.pay.PayInterface;
import com.alpha.common.utils.pay.util.PayConfig;
import com.alpha.module.app.model.PayDTO;
import com.alpha.common.utils.pay.util.PayUtil;
import com.alpha.common.utils.pay.util.WxPayUtil;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Component(value = "WeiXinPay")
public class WeiXinPay implements PayInterface {
    Map<String, String> wxConfig = null;

    @Override
    public void payRequest(PayDTO payDTO) {
        System.out.println("微信支付");
    }

    @Override
    public void pcPay(PayDTO payDTO) {
        System.out.println("微信Web支付");
    }

    @Override
    public String h5Pay(PayDTO payDTO) {
        try {
            initConfig(payDTO.getDomainName());
            if (wxConfig != null) {
                HashMap<String, String> wxParam = WxPayUtil.createWxParam(wxConfig, payDTO);
                wxParam.put("scene_info", "{\"h5_info\":{\"type\":\"Wap\",\"wap_url\":\"" + payDTO.getDomainName() + "\",\"wap_name\": \"订单支付\"}}");
                String sign = WxPayUtil.generateSignature(wxParam, wxConfig.get("secretKey"));
                wxParam.put("sign", sign);
                String dataXml = WxPayUtil.mapToXml(wxParam);
                String result = PayUtil.sendPost(WxPayUtil.URL_PAY_H5, dataXml);
                Map<String, String> resultMap = WxPayUtil.xmlToMap(result);
                if ("SUCCESS".equals(resultMap.get("result_code"))) {
                    Map<String, String> wxPayData = new HashMap<>();
                    String redirect_url = wxConfig.get("returnUrl") != null ? wxConfig.get("returnUrl") : payDTO.getDomainName();
                    String redirect_urlEncode = URLEncoder.encode(redirect_url, "utf-8");
                    String redirectUrl = resultMap.get("mweb_url") + "&redirect_url=" + redirect_urlEncode;
                    wxPayData.put("mweb_url", redirectUrl);
                    return wxPayData.toString();
                }
                return "";
            }
            return "";
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void appPay(PayDTO payDTO) {

    }

    @Override
    public void callBack(Map<String, String> params) {

    }

    private void initConfig(String domainName) {
        wxConfig = PayUtil.getPayConfig(domainName, PayConfig.WX_CONFIG);
    }
    public static void main(String[] args) {
        System.out.println(LocalDateTime.now().toString());
    }
}
